﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace PersonalWeb.Controller
{
    
    [Route("api/[controller]")]
    [ApiController]
    public class ToolsController : ControllerBase
    {
        [HttpGet]
        public IEnumerable<DownloadApp> Get()
        {
            List<DownloadApp>? appList = new List<DownloadApp>();
            try
            {
                FileInfo[] files = new DirectoryInfo(Program.appPath).GetFiles();
                foreach (var file in files)
                {
                    System.Diagnostics.FileVersionInfo info = System.Diagnostics.FileVersionInfo.GetVersionInfo(file.FullName);
                    var app = new DownloadApp
                    {
                        AppName = info.ProductName ?? string.Empty,
                        Titile = info.Comments ?? string.Empty,
                        UpdateTime = file.LastWriteTime,
                        Version = info.ProductVersion ?? "0.0.0.0",
                        Description = info.FileDescription ?? string.Empty,
                        DownloadPath = $"http://www.dickred.cn/api/tools/{file.Name}"
                    };
                    appList.Add(app);
                }
            }
            catch (Exception ex)
            {
                appList.Add(new DownloadApp() { AppName = string.Empty, Description= ex.ToString() });
            }
            return appList.ToArray();
        }

        /// <summary>
        /// 指定了文件名后，返回对应的工具
        /// </summary>
        /// <param name="toolName">工具文件名</param>
        /// <returns></returns>
        [HttpGet("{toolName}")]
        public async Task<IActionResult> Get(string toolName)
        {
            try
            {
                // 1. 大文件路径（假设是服务器上的大文件）
                string filePath = Path.Combine(Program.appPath, toolName);

                if (!System.IO.File.Exists(filePath))
                {
                    return NotFound();
                }

                // 2. 打开文件流（异步方式）
                FileStream fileStream = new FileStream(
                    filePath,
                    FileMode.Open,
                    FileAccess.Read,
                    FileShare.Read,
                    bufferSize: 4096, // 缓冲区大小（4KB）
                    useAsync: true // 启用异步 IO
                );

                // 3. MIME 类型（ZIP 文件）
                string contentType = "application/octet-stream";

                // 4. 返回 FileStreamResult（异步写入响应）
                return File(fileStream, contentType, toolName);
            }
            catch (Exception ex)
            {
                return StatusCode(StatusCodes.Status500InternalServerError, new { error = ex.Message });
            }
        }
    }

    public class DownloadApp
    {
        public string AppName { get; set; } = string.Empty;
        public string Titile { get; set; } = string.Empty;
        public DateTime UpdateTime { get; set; }
        public string Version { get; set; } = string.Empty;
        public string Description { get; set; } = string.Empty;
        public string DownloadPath { get; set; } = string.Empty;
    }
}
